package top.ytazwc.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;

/**
 * @author 00103943
 * @date 2025-03-17 09:29
 * @package top.ytazwc.zk
 * @Description 监听器示例
 */
public class zkListen {

    private static final String PATH = "/node1";

    private static final CuratorFramework CLIENT = CuratorFrameworkFactoryUtil.getCuratorFramework("127.0.0.1:12181");

    public static void main(String[] args) throws Exception {
        // 启动客户端
        CLIENT.start();
        PathChildrenCache pathChildrenCache = new PathChildrenCache(CLIENT, PATH, true);
        PathChildrenCacheListener listener = (client, event) -> {
            String eventType = event.getType().name(); // 获取事件类型枚举名
            String nodePath = (event.getData() != null) ? event.getData().getPath() : "null";
            System.out.printf("[DEBUG] 事件类型: %-12s | 节点路径: %s%n", eventType, nodePath);
        };
        // 先启动缓存再添加监听器 避免丢失初始事件
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);

        // 添加监听器之前查看监听器数量
        int listenerCount = pathChildrenCache.getListenable().size();
        System.out.println("活跃监听器数量: " + listenerCount);

        // 添加监听器
        pathChildrenCache.getListenable().addListener(listener);

        // 再次验证
        listenerCount = pathChildrenCache.getListenable().size();
        System.out.println("活跃监听器数量: " + listenerCount);

        // 调试断点建议
        System.out.println("断点位置: pathChildrenCache@" + System.identityHashCode(pathChildrenCache));

        // 调试node1
        CLIENT.create().creatingParentsIfNeeded().forPath("/node1/00001", "data".getBytes());
        CLIENT.create().creatingParentsIfNeeded().forPath("/node1/00002", "data".getBytes());

        CLIENT.setData().forPath("/node1/00002", "test".getBytes());

        pathChildrenCache.close();
        // 预期 0
        System.out.println("关闭后监听器数量: " + pathChildrenCache.getListenable().size());

    }

}
